<?php
/**
 * Created by PhpStorm.
 * User: zhao shou qiang
 * Date: 2018/1/09
 * Time: 11:50
 */

namespace backend\controllers;


use common\models\PackageInitiation;
use common\models\PackageLog;
use common\models\PackageTransferHistory;
use common\models\Package;
use common\models\PackageUpdateLog;
use Yii;
use yii\db\Exception;
use common\models\Responses;
use yii\filters\VerbFilter;

class PackageInitationController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return parent::behaviors();
    }

    /**
     * 资产包立项信息
     * @return string
     */
    public function actionBaseInfo()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $package_id = (int)Yii::$app->request->get('packageid');
            $type = (int)Yii::$app->request->post('type', 1); //1编辑， 2只读
            $post = Yii::$app->request->post();

            $id = (int)$post['PackageInitiation']['id'];
            $model = PackageInitiation::find()->where(['id' => $id])->one();
            if ($model !== null) {
                //编辑
                if ($type == 1) {
                    $state = false;
                    $changedAttributes = array();
                    foreach ($post['PackageInitiation'] as $key => $value) {
                        if ($model->$key != $value) {
                            $changedAttributes[$key] = $value;
                            $state = true;
                        }
                    }
                    if (!$state) {
                        return Responses::response400('没有做任何修改', true);
                    }

                    $transaction = Yii::$app->db->beginTransaction();
                    try {
                        //TODO 立项信息更新日志
                        $res = (new PackageInitiation())->setUpdateLog($model->id, $package_id, $changedAttributes, $userId, PackageUpdateLog::MODULE_SUBJECT, 2);
                        if (!$res['state']) {
                            throw new \Exception($res['msg']);
                        }

                        if (($model->load($post) && $model->save())) {
                            $transaction->commit();
                            return Responses::response200($model, 1, '保存成功');
                        } else {
                            $error = $model->getFirstErrors();
                            $message = '';
                            if (!empty($error)) {
                                foreach ($error as $value) {
                                    $message .= $value;
                                }
                                $tmpStr = strip_tags($message);
                                $tmpLen = mb_strlen($tmpStr);
                                $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                            }
                            throw new \Exception($message);
                        }
                    } catch (\Exception $e) {
                        $transaction->rollBack();
                        $message = $e->getMessage();
                        return Responses::response400($message, true);
                    } catch (\Throwable $e) {
                        $transaction->rollBack();
                        $message = $e->getMessage();
                        return Responses::response400($message, true);
                    }

//                    if (($model->load($post) && $model->save())) {
//                        return Responses::response200($model, 1, '保存成功');
//                    } else {
//                        $error = $model->getFirstErrors();
//                        $message = '';
//                        if (!empty($error)) {
//                            foreach ($error as $value) {
//                                $message .= $value;
//                            }
//                            $tmpStr = strip_tags($message);
//                            $tmpLen = mb_strlen($tmpStr);
//                            $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
//                        }
//                        return Responses::response400($message, true);
//                    }
                    //查询
                } elseif ($type == 2) {
                    return Responses::response200($model, 1, '保存成功');
                }
            } else {
                return Responses::response400('该立项信息不存在', true);
            }
        }
    }

    /**
     * 立项信息
     * @return array
     */
    public function actionBase()
    {
        if (Yii::$app->request->isAjax) {
            $userId = Yii::$app->user->id;
            $package_id = (int)Yii::$app->request->get('package_id');
            $type = (int)Yii::$app->request->get('type');
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            //只读
            if ($type === 2) {
                $packageInitation = PackageInitiation::find()->where('package_id=:id', [':id' => $package_id])->one(); //asArray()
                if ($packageInitation !== null) {

                    //判断是否加锁
                    $isLockedData = $this->is_locked($packageInitation, $userId);
                    if (!$isLockedData['state']) {
                        return Responses::response400($isLockedData['msg'], true);
                    }

                    //加锁
                    $lockData = $this->locking($packageInitation, $userId);
                    if (!$lockData['state']) {
                        return Responses::response400($lockData['msg'], true);
                    }

                    $packageInitation->bargain = $this->set_number_format2($packageInitation->bargain);
                    $str = $this->renderPartial('@app/views/package/investigation/initation-edit.php', ['data' => $packageInitation]);
                    return Responses::response200($str, 1, '切换成功');
                }
                return Responses::response400('该立资产包未立项', true);

                //编辑
            } elseif ($type === 1) {
                $post = Yii::$app->request->post();
                $id = (int)$post['PackageInitiation']['id'];
                $model = PackageInitiation::find()->where(['id' => $id, 'package_id' => $package_id])->one();
                if ($model !== null) {
                    //判断是否加锁
                    $isLockedData = $this->is_locked($model, $userId);
                    if (!$isLockedData['state']) {
                        return Responses::response400($isLockedData['msg'], true);
                    }

                    $state = false;
                    $changedAttributes = array();
                    foreach ($post['PackageInitiation'] as $key => $value) {
                        //当前卖方报价 (预估售价)
                        if ($key == 'bargain') {
                            $value = $this->set_number_format($value);
                        }
                        if ($model->$key != $value) {
                            $changedAttributes[$key] = $value;
                            $state = true;
                        }
                    }

                    if (!$state) {
                        $model->bargain = $this->set_number_format2($model->bargain);
                        $str = $this->renderPartial('@app/views/package/investigation/initation.php', ['data' => $model]);
                        return Responses::response200($str, 1, '保存成功');
                        //return Responses::response400('没有做任何修改', true);
                    }

                    $transaction = Yii::$app->db->beginTransaction();
                    try {
                        //TODO 立项信息更新日志
                        $res = (new PackageInitiation())->setUpdateLog($model->id, $package_id, $changedAttributes, $userId, PackageUpdateLog::MODULE_SUBJECT, 2);
                        if (!$res['state']) {
                            throw new \Exception($res['msg']);
                        }

                        $post['PackageInitiation']['bargain'] = $this->set_number_format($post['PackageInitiation']['bargain']);
                        $post['PackageInitiation']['lock_user'] = null;
                        $post['PackageInitiation']['lock_timestamp'] = null;
                        if (($model->load($post) && $model->save())) {

                            $transaction->commit();

                            $model->bargain = $this->set_number_format2($model->bargain);
                            $str = $this->renderPartial('@app/views/package/investigation/initation.php', ['data' => $model]);
                            //---编辑资产包-发送消息--fly---
                            PackageController::actionPostMessage($package_id);
                            //---编辑资产包-发送消息--fly---
                            return Responses::response200($str, 1, '保存成功');
                        } else {
                            $error = $model->getFirstErrors();
                            $message = '';
                            if (!empty($error)) {
                                foreach ($error as $value) {
                                    $message .= $value;
                                }
                                $tmpStr = strip_tags($message);
                                $tmpLen = mb_strlen($tmpStr);
                                $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                            }
                            throw new \Exception($message);
                        }
                    } catch (\Exception $e) {
                        $transaction->rollBack();
                        $message = $e->getMessage();
                        return Responses::response400($message, true);
                    } catch (\Throwable $e) {
                        $transaction->rollBack();
                        $message = $e->getMessage();
                        return Responses::response400($message, true);
                    }
                } else {
                    return Responses::response400('该立项信息不存在', true);
                }

                //取消页面
            } elseif ($type === 3) {
                $post = Yii::$app->request->post();
                $id = (int)$post['PackageInitiation']['id'];
                $packageInitation = PackageInitiation::find()->where(['id' => $id, 'package_id' => $package_id])->one(); //asArray()
                if ($packageInitation !== null) {
                    //解锁
                    $unlockindData = $this->unlocking($packageInitation, $userId);
                    if (!$unlockindData['state']) {
                        return Responses::response400($unlockindData['msg'], true);
                    }

                    $packageInitation->bargain = $this->set_number_format2($packageInitation->bargain);
                    $str = $this->renderPartial('@app/views/package/investigation/initation.php', ['data' => $packageInitation]);
                    return Responses::response200($str, 1, '切换成功');
                }
                return Responses::response400('该立项信息不存在', true);
            }
        }
    }

    /**
     * 资产包其他立项信息
     * @return string
     */
    public function actionBaseOther()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $type = (int)Yii::$app->request->get('type');
            $post = Yii::$app->request->post();

            if ($type == 3) {
                $other_id = (int)Yii::$app->request->get('other_id');
                $model = PackageInitiation::findOne($other_id);
                if ($model !== null) {
                    //判断是否加锁
                    $isLockedData = $this->is_locked($model, $userId);
                    if (!$isLockedData['state']) {
                        return Responses::response400($isLockedData['msg'], true);
                    }

                    //加锁
                    $lockData = $this->locking($model, $userId);
                    if ($lockData['state']) {
                        return Responses::response200($model, 1, '切换成功');
                    }
                }
                return Responses::response400('该资产包未立项', true);
            } else {
                $id = (int)$post['PackageInitiation']['id'];
                $model = PackageInitiation::find()->where(['id' => $id])->one();
                if ($model !== null) {
                    //编辑
                    if ($type == 1) {
                        $state = false;
                        $changedAttributes = array();
                        foreach ($post['PackageInitiation'] as $key => $value) {
                            if ($model->$key != $value) {
                                $changedAttributes[$key] = $value;
                                $state = true;
                            }
                        }
//                    if (!$state) {
//                        return Responses::response400('没有任何修改', true);
//                    }

                        //判断是否加锁
                        $isLockedData = $this->is_locked($model, $userId);
                        if (!$isLockedData['state']) {
                            return Responses::response400($isLockedData['msg'], true);
                        }

                        $transaction = Yii::$app->db->beginTransaction();
                        try {
                            //TODO 立项信息更新日志
                            $res = (new PackageInitiation())->setUpdateLog($model->id, $model->package_id, $changedAttributes, $userId, PackageUpdateLog::MODULE_OTHER, 2);
                            if (!$res['state']) {
                                throw new \Exception($res['msg']);
                            }

                            $post['PackageInitiation']['lock_user'] = null;
                            $post['PackageInitiation']['lock_timestamp'] = null;
                            if (($model->load($post) && $model->save())) {
                                //---编辑资产包-发送消息--fly---
                                PackageController::actionPostMessage($model->package_id);
                                //---编辑资产包-发送消息--fly---
                                $transaction->commit();
                                return Responses::response200($model, 1, '保存成功');
                            } else {
                                $error = $model->getFirstErrors();
                                $message = '';
                                if (!empty($error)) {
                                    foreach ($error as $value) {
                                        $message .= $value;
                                    }
                                    $tmpStr = strip_tags($message);
                                    $tmpLen = mb_strlen($tmpStr);
                                    $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                                }
                                throw new \Exception($message);
                            }

                        } catch (\Exception $e) {
                            $transaction->rollBack();
                            $message = $e->getMessage();
                            return Responses::response400($message, true);
                        } catch (\Throwable $e) {
                            $transaction->rollBack();
                            $message = $e->getMessage();
                            return Responses::response400($message, true);
                        }

                        //查询
                    } elseif ($type == 2) {
                        //解锁
                        $unlockindData = $this->unlocking($model, $userId);
                        if (!$unlockindData['state']) {
                            return Responses::response400($unlockindData['msg'], true);
                        }
                        return Responses::response200($model, 1, '取消成功');
                    }
                } else {
                    return Responses::response400('该资产包未立项', true);
                }
            }
        }
    }

    /**
     * 资产包立项报价信息
     * @return string
     */
    public function actionPriceDetail()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $type = (int)Yii::$app->request->get('type');
            $package_id = (int)Yii::$app->request->get('package_id');

            switch ($type) {
                //编辑
                case 1:
                    $post = Yii::$app->request->post();
                    $id = (int)$post['PackageInitiation']['id'];
                    $model = PackageInitiation::find()->where(['id' => $id, 'package_id' => $package_id])->one();
                    if ($model !== null) {
                        //判断是否加锁
                        $isLockedData = $this->is_locked($model, $userId);
                        if (!$isLockedData['state']) {
                            return Responses::response400($isLockedData['msg'], true);
                        }

                        $state = false;
                        $changedAttributes = array();
                        foreach ($post['PackageInitiation'] as $key => $value) {
                            if ($model->$key != $value) {
                                $changedAttributes[$key] = $value;
                                $state = true;
                            }
                        }

//                        if (!$state) {
//                            return Responses::response400('没有做任何修改', true);
//                        }

                        $transaction = Yii::$app->db->beginTransaction();
                        try {
                            //TODO 报价信息更新日志
                            $res = (new PackageInitiation())->setUpdateLog($model->id, $package_id, $changedAttributes, $userId, PackageUpdateLog::MODULE_QUOTE, 2);
                            if (!$res['state']) {
                                throw new \Exception($res['msg']);
                            }

                            //编辑资产包
                            $post['PackageInitiation']['lock_user'] = null;
                            $post['PackageInitiation']['lock_timestamp'] = null;
                            if (($model->load($post) && $model->save())) {
                                $transaction->commit();

                                $str = $this->renderPartial('@app/views/package/investigation/price-detail.php', ['data' => $model]);
                                //---编辑资产包-发送消息--fly---
                                PackageController::actionPostMessage($package_id);
                                //---编辑资产包-发送消息--fly---
                                return Responses::response200($str, 1, '保存成功');
                            } else {
                                $error = $model->getFirstErrors();
                                $message = '';
                                if (!empty($error)) {
                                    foreach ($error as $value) {
                                        $message .= $value;
                                    }
                                    $tmpStr = strip_tags($message);
                                    $tmpLen = mb_strlen($tmpStr);
                                    $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                                }
                                throw new \Exception($message);
                            }
                        } catch (\Exception $e) {
                            $transaction->rollBack();
                            $message = $e->getMessage();
                            return Responses::response400($message, true);
                        } catch (\Throwable $e) {
                            $transaction->rollBack();
                            $message = $e->getMessage();
                            return Responses::response400($message, true);
                        }
                    } else {
                        return Responses::response400('该资产包未立项', true);
                    }
                    break;
                //切换编辑
                case 2:
                    $packageInitation = PackageInitiation::find()->where('package_id=:id', [':id' => $package_id])->one();
                    if ($packageInitation !== null) {
                        //判断是否加锁
                        $isLockedData = $this->is_locked($packageInitation, $userId);
                        if (!$isLockedData['state']) {
                            return Responses::response400($isLockedData['msg'], true);
                        }

                        //加锁
                        $lockData = $this->locking($packageInitation, $userId);
                        if (!$lockData['state']) {
                            return Responses::response400($lockData['msg'], true);
                        }

                        $str = $this->renderPartial('@app/views/package/investigation/price-detail-edit.php', ['data' => $packageInitation]);
                        return Responses::response200($str, 1, '切换成功');
                    } else {
                        return Responses::response400('该资产包未立项', true);
                    }
                    break;
                //切换只读
                case 3:
                    $packageInitation = PackageInitiation::find()->where('package_id=:id', [':id' => $package_id])->one();
                    if ($packageInitation !== null) {
                        //解锁
                        $unlockindData = $this->unlocking($packageInitation, $userId);
                        if (!$unlockindData['state']) {
                            return Responses::response400($unlockindData['msg'], true);
                        }

                        $str = $this->renderPartial('@app/views/package/investigation/price-detail.php', ['data' => $packageInitation]);
                        return Responses::response200($str, 1, '切换成功');
                    } else {
                        return Responses::response400('该资产包未立项', true);
                    }
                    break;
                default;
            }
        }
    }

    /**
     * 资产包立项流转、前期处置及维护情况
     * @return array
     */
    public function actionTransferHistory()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $package_id = (int)Yii::$app->request->post('package_id');
            $type = (int)Yii::$app->request->post('type');
            $model = new PackageTransferHistory();
            $list = $model->getList(['package_id' => $package_id]);
            if (empty($list)) {
                $packageTransferHistory = new PackageTransferHistory();
                $packageTransferHistory->package_id = $package_id;
                $packageTransferHistory->transfer_date = '';
                $packageTransferHistory->transfer = '';
                $packageTransferHistory->content = '';
                $packageTransferHistory->remark = '';
                $packageTransferHistory->created_at = date('Y-m-d H:i:s',time());
                $packageTransferHistory->order = 1;
                $packageTransferHistory->save();
                $list = PackageTransferHistory::find()->where(['package_id'=>$package_id])->orderBy('order DESC')->asArray()->all();
            }

            //切换编辑页面
            if ($type == 1) {
                //---编辑资产包-发送消息--fly---
                PackageController::actionPostMessage($package_id);
                //---编辑资产包-发送消息--fly---
                $str = $this->renderPartial('@app/views/package/investigation/transfer-history-edit.php', ['list' => $list]);
                return Responses::response200($str, 1, '切换成功');

                //切换只读页面
            } elseif ($type == 2) {
                $str = $this->renderPartial('@app/views/package/investigation/transfer-history.php', ['list' => $list]);
                return Responses::response200($str, 1, '取消成功');

            }
        }
    }


    /**
     * 添加流转、前期处置及维护情况
     *      轮循资产包流转历中记录，当列表中order大于当前order 加一，并添加当前数据（order+1）
     * @return array
     */
    public function actionAddTransferHistory()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $post = Yii::$app->request->post();
            $package_id = (int)$post['package_id'];
            $order = (int)$post['order'];

            $transaction = Yii::$app->db->beginTransaction();
            try {
                $data = $this->pollTransferHistory($package_id, $order, 1);
                if (!$data['state']) {
                    throw new Exception($data['msg']);
                }

                $model = new PackageTransferHistory();
                $model->package_id = $package_id;
                $model->transfer_date = $post['transfer_date'];
                $model->transfer = $post['transfer'];
                $model->content = $post['content'];
                $model->remark = $post['remark'];
                $model->order = $order + 1;
                $model->created_at = date('Y-m-d H:i:s', time());
                if (!$model->save()) {
                    $error = $model->getFirstErrors();
                    $message = '';
                    if (!empty($error)) {
                        foreach ($error as $value) {
                            $message .= $value;
                        }
                        $tmpStr = strip_tags($message);
                        $tmpLen = mb_strlen($tmpStr);
                        $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                    }
                    throw new Exception($message);
                } else {
                    //TODO 添加资产包流转日志
                    $res = $model->setUpdateLog($model->id, $package_id, $model, $userId, PackageUpdateLog::MODULE_CONVERSION, 1);
                    if (!$res['state']) {
                        throw new Exception($res['msg']);
                    }
                }
                $transaction->commit();
                $list2 = $model->getList(['package_id' => $package_id]);
                $str = $this->renderPartial('@app/views/package/investigation/transfer-history-edit.php', ['list' => $list2]);
                //---编辑资产包-发送消息--fly---
                PackageController::actionPostMessage($package_id);
                //---编辑资产包-发送消息--fly---
                return Responses::response200($str, 1, '添加成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 删除流转、前期处置及维护情况
     *      轮循资产包流转历中记录，当列表中order大于当前order 减一，并添加当前数据（order-1）
     * @return array
     */
    public function actionDeleteTransferHistory()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $post = Yii::$app->request->post();
            $package_id = (int)$post['package_id'];
            $order = (int)$post['order'];
            $id = (int)$post['id'];

            $transaction = Yii::$app->db->beginTransaction();
            try {
                $data = $this->pollTransferHistory($package_id, $order, 2);
                if (!$data['state']) {
                    throw new Exception($data['msg']);
                }

                $model = PackageTransferHistory::find()->where(['package_id' => $package_id, 'id' => $id])->one();
                if ($model === null) {
                    throw new Exception('该数据不存在');
                }

                //TODO 添加资产包流转日志
                $res = (new PackageTransferHistory)->setUpdateLog($id, $package_id, array(), $userId, PackageUpdateLog::MODULE_CONVERSION, 3);
                if (!$res['state']) {
                    throw new Exception($res['msg']);
                }

                if (!$model->delete()) {
                    throw new Exception('删除失败');
                }
                //---编辑资产包-发送消息--fly---
                PackageController::actionPostMessage($package_id);
                //---编辑资产包-发送消息--fly---
                $transaction->commit();
                //$list2 = (new PackageTransferHistory)->getList(['package_id' => $package_id]);
                //$str = $this->renderPartial('@app/views/package/investigation/transfer-history-edit.php', ['list' => $list2]);
                //return Responses::response200($str, 1, '删除成功');
                return Responses::response200('', 1, '删除成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }

    /**
     * 保存流转、前期处置及维护情况
     *      轮循每列，
     *          若order>0, 数据改变则保存，否则跳出本次循环
     *          若order=0，则新增
     *      若总得未改变，则提示数据未改变
     * @return array
     */
    public function actionSavesTransferHistory()
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $userId = Yii::$app->user->id;
            $package_id = (int)Yii::$app->request->get('package_id');
            $post = Yii::$app->request->post();
            $data = $post['PackageTransferHistory'];

            $transaction = Yii::$app->db->beginTransaction();
            $status = false;
            try {
                for ($i = 0; $i < count($data['id']); $i++) {
                    $packageTransferHistory = new PackageTransferHistory();
                    //新增
                    if ($data['id'][$i] == 0) {
                        $model = clone $packageTransferHistory;
                        $model->package_id = (int)$package_id;
                        $model->transfer_date = $data['transfer_date'][$i];
                        $model->transfer = $data['transfer'][$i];
                        $model->content = $data['content'][$i];
                        $model->remark = $data['remark'][$i];
                        //$model->order = $data['order'][$i] + 1;
                        $model->order = $i + 1;
                        $model->created_at = date('Y-m-d H:i:s', time());
                        if (!$model->save()) {
                            $error = $model->getFirstErrors();
                            $message = '';
                            if (!empty($error)) {
                                foreach ($error as $value) {
                                    $message .= $value;
                                }
                                $tmpStr = strip_tags($message);
                                $tmpLen = mb_strlen($tmpStr);
                                $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                            }
                            throw new Exception("第" . ($i + 1) . "行保存失败，失败原因：{$message}");
                        } else {

                            //TODO 添加资产包更新日志
                            $res = $packageTransferHistory->setUpdateLog($model->id, $package_id, $model, $userId, PackageUpdateLog::MODULE_CONVERSION, 1);
                            if (!$res['state']) {
                                throw new \Exception($res['msg']);
                            }
                            $status = true;
                        }
                        //编辑
                    } else {
                        $model = PackageTransferHistory::findOne((int)$data['id'][$i]);
                        if ($model === null) {
                            throw new Exception("第" . ($i + 1) . "行数据查不到");
                        }
                        $state = false;
                        $changedAttributes = array();
                        if ($model->transfer_date != $data['transfer_date'][$i]) {
                            $model->transfer_date = $data['transfer_date'][$i];
                            $changedAttributes['transfer_date'] = $data['transfer_date'][$i];
                            $state = true;
                        }

                        if ($model->transfer != $data['transfer'][$i]) {
                            $model->transfer = $data['transfer'][$i];
                            $changedAttributes['transfer'] = $data['transfer'][$i];
                            $state = true;
                        }

                        if ($model->content != $data['content'][$i]) {
                            $model->content = $data['content'][$i];
                            $changedAttributes['content'] = $data['content'][$i];
                            $state = true;
                        }

                        if ($model->remark != $data['remark'][$i]) {
                            $model->remark = $data['remark'][$i];
                            $changedAttributes['remark'] = $data['remark'][$i];
                            $state = true;
                        }

                        /*if ($model->order != $data['order'][$i]) {
                            $model->order = $data['order'][$i];
                            $changedAttributes['order'] = $data['order'][$i];
                            $state = true;
                        }*/

                        if ($model->order != $i + 1) {
                            $model->order = $i + 1;
                            $changedAttributes['order'] = $i + 1;
                            $state = true;
                        }

                        if ($state === false) {
                            continue;
                        }

                        //TODO 添加资产包更新日志
                        $res = $packageTransferHistory->setUpdateLog($model->id, $package_id, $changedAttributes, $userId, PackageUpdateLog::MODULE_CONVERSION, 2);
                        if (!$res['state']) {
                            throw new \Exception($res['msg']);
                        }

                        if (!$model->save()) {
                            $error = $model->getFirstErrors();
                            $message = '';
                            if (!empty($error)) {
                                foreach ($error as $value) {
                                    $message .= $value;
                                }
                                $tmpStr = strip_tags($message);
                                $tmpLen = mb_strlen($tmpStr);
                                $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                            }
                            throw new Exception("第" . ($i + 1) . "行保存失败，失败原因：{$message}");
                        } else {
                            $status = true;
                        }
                    }
                }
                if ($status === false) {
                    $packageTransferHistory = new PackageTransferHistory();
                    $list = $packageTransferHistory->getList(['package_id' => $package_id]);
                    $str = $this->renderPartial('@app/views/package/investigation/transfer-history.php', ['list' => $list]);
                    //return Responses::response400('数据未改变', true);
                    return Responses::response200($str, 1, '保存成功');
                }
                $transaction->commit();
                $packageTransferHistory = new PackageTransferHistory();
                $list = $packageTransferHistory->getList(['package_id' => $package_id]);
                //---编辑资产包-发送消息--fly---
                PackageController::actionPostMessage($package_id);
                //---编辑资产包-发送消息--fly---
                $str = $this->renderPartial('@app/views/package/investigation/transfer-history.php', ['list' => $list]);
                return Responses::response200($str, 1, '保存成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            } catch (\Throwable $e) {
                $transaction->rollBack();
                $message = $e->getMessage();
                return Responses::response400($message, true);
            }
        }
    }


    /**
     * 轮循资产包流转历中记录
     *      $type=1
     *              当列表中order大于当前order 加一，并添加当前数据（order+1）
     *      $type=2
     *              当列表中order大于当前order 减一，并添加当前数据（order-1）
     * @param $package_id 资产包id
     * @param $order 当前排序
     * @param $type 类型
     * @return array 结果
     */
    protected function pollTransferHistory($package_id, $order, $type)
    {
        $model = new PackageTransferHistory();
        $list = $model->getList(['package_id' => $package_id]);
        if (!empty($list) && is_array($list)) {
            foreach ($list as $value) {
                if ($value['order'] > $order) {
                    $packageTransferHistory = PackageTransferHistory::findOne($value['id']);
                    if ($type == 1) {
                        $packageTransferHistory->order = $packageTransferHistory->order + 1;
                    } elseif ($type == 2) {
                        $packageTransferHistory->order = $packageTransferHistory->order - 1;
                    }
                    if (!$packageTransferHistory->save()) {
                        $error = $model->getFirstErrors();
                        $message = '';
                        if (!empty($error)) {
                            foreach ($error as $value) {
                                $message .= $value;
                            }
                            $tmpStr = strip_tags($message);
                            $tmpLen = mb_strlen($tmpStr);
                            $message = mb_substr($tmpStr, 0, $tmpLen, 'utf-8');
                        }
                        return array('state' => false, 'msg' => $message);
                    }
                }
            }
        }
        return array('state' => true, 'msg' => '');
    }

}
